// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package watch_cmd

import (
	"fmt"

	"gitcode.com/openseaotter/so_proto_gen_go.git/watch_api"
	"gitcode.com/openseaotter/so_server/config"
	"gitcode.com/openseaotter/so_server/utils"
	"github.com/spf13/cobra"
)

var updateCmd_Desc string

var updateCmd = &cobra.Command{
	Use: "update",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) <= 1 {
			return fmt.Errorf("need param [watchId] [group1/image1] ... [groupn/imagen]")
		}
		return nil
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		cfg, err := config.ReadServerConfig()
		if err != nil {
			return err
		}
		if cfg.SuperToken == "" {
			return fmt.Errorf("miss super token in config")
		}
		conn, err := utils.ConnGrpcServer(fmt.Sprintf("127.0.0.1:%d", cfg.ServicePort))
		if err != nil {
			return err
		}
		defer conn.Close()

		client := watch_api.NewWatchApiClient(conn)

		watchId := args[0]
		fullImagenameList := args[1:]

		res, err := client.Update(cmd.Context(), &watch_api.UpdateRequest{
			AccessToken:       cfg.SuperToken,
			WatchId:           watchId,
			FullImageNameList: fullImagenameList,
			Desc:              updateCmd_Desc,
		})
		if err != nil {
			return err
		}
		if res.Code != watch_api.UpdateResponse_CODE_OK {
			return fmt.Errorf("%s", res.ErrMsg)
		}
		fmt.Println("update watch info success")
		return nil
	},
}

func init() {
	updateCmd.Flags().StringVar(&updateCmd_Desc, "desc", "", "set watch desc")
}
